import React from 'react'
import {Form, Button, Input, Affix, Row, Col, message, Modal} from 'antd'
import backlashService from './pay-backlash.service'
import menuRoute from 'routes/menuRoute'
import PayDetail from 'containers/pay/pay-workbench/payment-detail' //支付详情
import ApproveHistory from "./approve-history-work-flow"
import {Alert} from 'antd';
import {deepFullCopy, messages, queryCurrencyPrecision} from 'share/common'
import Upload from 'components/upload-button';
const FormItem = Form.Item;
const {TextArea} = Input;

class NewPayRefund extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      queryFlag: true,
      draweeAccountNumber: [],
      payeeAccountNumber: [],
      currencyList: [],//币种
      data: {},
      abledRefundAmount: 0,
      showDetail: false,
      detailFlag: '',
      documentInfo: {},
      sourceDetail: {},
      backlashDetail: {},
      backlashFlag: false,
      showChild: false,
      detailId: undefined,
      saveData: {},//保存后返回新的支付数据
      saveFlag: false,//是否已经保存
      btnLoading: false,//按钮加载
      showButtonFlag: true,
      historyLoading: false,
      uploadOIDs: [], //上传附件的OIDs
      fileList: [],
      fileShow: false,
      backlashDetailRemark: true,
      alert_message: {},
      alert_des: {},
      alert_type: {},
      alert_warning: false,
      alert_seccuss: false,
      alert_fail: false,
    }
  }

  componentWillReceiveProps(nextProps) {
    const record = nextProps.params.record;
    if (record && this.state.queryFlag && nextProps.params.flag) {//查询
      let flashFlag = record.flashFlag;
      if (record.backDetail) {
        let data = deepFullCopy(record) || {};
        let documentInfo = data.payDocumentDTO;
        let sourceDetail = data.detail;
        let backlashDetail = data.backDetail;
        if (backlashDetail && !flashFlag) {
          let fileList = [];
          if (backlashDetail.backlashAttachments) {
            backlashDetail.backlashAttachments.map(item => {
              fileList.push({
                ...item,
                uid: item.id,
                name: item.fileName,
                status: "done"
              })
            })
          }
          if (backlashDetail.paymentStatus === "N" || backlashDetail.paymentStatus === "F") {//如果是编辑中或者驳回，则可以发起反冲
            this.setState({
              queryFlag: false,
              data: data,
              documentInfo: documentInfo,
              sourceDetail: sourceDetail,
              backlashDetail: backlashDetail,
              showDetail: true,
              alert_fail: backlashDetail.paymentStatus === "F",
              backlashDetailRemark: true,
              fileList: fileList,
              alert_warning: false,
              alert_seccuss: false,
              fileShow: true,
              uploadOIDs: backlashDetail.backlashAttachmentOID
            },() => {
              this.getApproveHistory();
            });
          } else if (backlashDetail.paymentStatus === "P") {//其他状态则隐藏下部4个按钮，且描述不是输入框
            this.setState({
              queryFlag: false,
              data: data,
              documentInfo: documentInfo,
              sourceDetail: sourceDetail,
              backlashDetail: backlashDetail,
              showDetail: true,
              showButtonFlag: false,
              historyLoading: true,
              backlashDetailRemark: false,
              fileList: fileList,
              alert_warning: true,
              alert_seccuss: false,
              alert_fail: false,
              fileShow: true,
              uploadOIDs: backlashDetail.backlashAttachmentOID
            },() => {
              this.getApproveHistory();
            });
          } else if (backlashDetail.paymentStatus === "S") {
            this.setState({
              queryFlag: false,
              data: data,
              documentInfo: documentInfo,
              sourceDetail: sourceDetail,
              backlashDetail: backlashDetail,
              showDetail: true,
              showButtonFlag: false,
              historyLoading: true,
              backlashDetailRemark: false,
              fileList: fileList,
              alert_seccuss: true,
              alert_warning: false,
              alert_fail: false,
              fileShow: true,
              uploadOIDs: backlashDetail.backlashAttachmentOID
            },() => {
              this.getApproveHistory();
            });
          }
        } else {
          this.setState({
            queryFlag: false,
            data: data,
            documentInfo: documentInfo,
            sourceDetail: sourceDetail,
          });
        }
      } else {
        this.setState({
          queryFlag: false,
          data: record || {},
          documentInfo: record.payDocumentDTO,
          sourceDetail: record.detail,
        });
      }
    }
    if (this.props.params.flag && !nextProps.params.flag) {
      this.setState({
        queryFlag: true,
        draweeAccountNumber: [],
        payeeAccountNumber: [],
        saveFlag: false,
        showButtonFlag: true,
        showDetail: false
      });
      this.props.form.resetFields();
    }
  }

  getApproveHistory = () => {
    this.setState({
      historyLoading: true
    });
    let id = this.state.backlashDetail.id;
    backlashService.getBacklashHistory(id).then(res => {
      this.setState({historyLoading: false}, () => {
        this.setState({approveHistory: res.data})
      })
    }).catch(() => {
      message.error(messages('pay.key192')/*反冲历史加载失败，请重试*/);
      this.setState({historyLoading: false});
    })
  };

  onCancel = () => {
    this.props.close();
    this.props.form.resetFields();
    this.setState({
      showButtonFlag: true,
      showDetail: false
    })
  };

  //弹出框关闭
  onClose = () => {
    this.setState({
      showChild: false
    })
  };

  /**
   * 组装方法
   * @param content 内部组件
   * @return {*} 给组件添加this.props.close(params)方法,params为返回到最外层的值
   *             同时添加外部传入的props为内部组件可用
   */
  wrapClose = (content) => {
    let id = this.state.detailId;
    const newProps = {
      params: {id: id, refund: true}
    };
    return React.createElement(content, Object.assign({}, newProps.params, newProps));
  };

  doBacklash = (e) => {
    e.preventDefault();
    //发起反冲，生成反冲数据
    let detailId = this.state.data.detail.id;
    let data = this.state.data;
    let remarks = this.props.form.getFieldValue("remarks");
    loading:true;
    if (this.state.showDetail) {//添加备注，附件
      let updateParam = {
        "id": data.backDetail.id,
        "remarks": remarks,
        "attachmentOIDS": this.state.uploadOIDs
      };
      backlashService.updateByDetailId(updateParam).then(
        res => {
          if (res.status === 200) {
            loading:false;
            message.success(messages('pay.key193')/*保存成功*/);
            let data = res.data || {};
            let documentInfo = data.payDocumentDTO;
            let sourceDetail = data.detail;
            let backlashDetail = data.backDetail;
            this.setState({
              data: data,
              documentInfo: documentInfo,
              sourceDetail: sourceDetail,
              backlashDetail: backlashDetail,
              backlashFlag: true,
              showDetail: true,
              backlashDetailRemark: true
            });
          }
        }
      )
    } else {//发起反冲
      backlashService.getBacklashByDetailId(detailId).then(
        res => {
          if (res.status === 200) {
            let data = res.data || {};
            let documentInfo = data.payDocumentDTO;
            let sourceDetail = data.detail;
            let backlashDetail = data.backDetail;
            let fileList = [];
            if (backlashDetail.backlashAttachments) {
              backlashDetail.backlashAttachments.map(item => {
                fileList.push({
                  ...item,
                  uid: item.id,
                  name: item.fileName,
                  status: "done"
                })
              })
            }
            this.setState({
              data: data,
              documentInfo: documentInfo,
              sourceDetail: sourceDetail,
              backlashDetail: backlashDetail,
              backlashFlag: true,
              showDetail: true,
              backlashDetailRemark: true,
              fileList: fileList,
              fileShow: true,
            });
          }
        }
      );
    }
  };

  //上传附件
  handleUpload = (OIDs) => {
    this.setState({uploadOIDs: OIDs})
  };

  //点击提交
  onSubmit = () => {
    const a = this;
    Modal.confirm({
      title: messages('pay.key194')/*确认反冲吗?*/,
      content: messages('pay.key195')/*反冲后需要进行复核!*/,
      okText: messages('common.ok')/*确定*/,
      cancelText: messages('common.cancel')/*取消*/,
      onOk: () => {
        let backDetail = this.state.backlashDetail;
        let backDetailId = backDetail.id;
        backlashService.submitBacklash(backDetailId).then(
          res => {
            if (res.status === 200) {
              //提交成功后进入反冲查询页面，暂时不跳
              message.success(messages('pay.key196')/*提交成功*/);
              payCanBacklash:  menuRoute.getRouteItem('main-pay-backlash', 'key');    //发起反冲页面
              this.onCancel()
            }
          }
        ).catch(e => {
          a.setState({queryFlag: false});
          message.error(e.response.data.message);
          a.onCancel()
        });
      },
      onCancel() {},
    });
  };

  //查看支付流水详情
  viewPayDetail = (id) => {
    this.setState({
      showChild: true,
      detailId: id,
      detailFlag: 'PAYDETAIL'
    })
  };

  //查看单据详情
  viewDocumentDetail = (id, documentCategory) => {
    /*this.setState({
      showChild:  true,
      detailId:id,

      detailFlag:'DECUMENT'
    })*/
  };

  // 上传附件成功回调
  handleUpload = (OIDs) => {
    this.setState({uploadOIDs: OIDs});
  };

  //点击删除
  onDelete = () => {
    Modal.confirm({
      title: messages('pay.key197')/*确认删除这条数据?*/,
      content: messages('pay.key198')/*删除后可以重新添加反冲信息!*/,
      okText: messages('common.ok')/*确定*/,
      cancelText: messages('common.cancel')/*取消*/,
      onOk: () => {
        let backDetail = this.state.backlashDetail;
        loading:true
        let backDetailId = backDetail.id;
        backlashService.deleteBacklashDetailById(backDetailId).then(
          response => {
            if (response.status === 200) {
              message.success(messages('common.delete.successful')/*删除成功*/);
              this.onCancel();
            }
          }
        );
      },
      onCancel() {},
    });
  };

  render() {
    const {getFieldDecorator} = this.props.form;
    const { params } = this.props;
    const {showButtonFlag, documentInfo, fileList, sourceDetail, backlashDetail, alert_fail, alert_warning, alert_seccuss, showDetail, showChild, backlashDetailRemark, btnLoading, detailFlag} = this.state;
    let newButton = showButtonFlag ? (
      <div className="slide-footer">
        {
          params.isCan && <Button onClick={this.onSubmit} type="primary">{messages('common.submit')}</Button>
        }
        {/*<Button type="primary" htmlType="submit" loading={btnLoading}>{messages('common.save')}</Button>*/}
        <Button onClick={this.onCancel}>{messages('common.back')/*返回*/}</Button>
        <Button onClick={() => {
          this.onDelete()
        }} style={{
          color: '#fff',
          background: '#f04134',
          'border-color': '#f04134'
        }}>{messages('common.delete')/*删除*/}</Button>
      </div>
    ) : (
      <div className="slide-footer">
        <Button onClick={this.onCancel}>{messages('common.back')/*返回*/}</Button>
      </div>
    );
    let approveButton = (<div className="slide-footer">
      <Button type="primary" htmlType="submit" loading={false}
              style={{margin: '0 20px'}}>{messages('pay.key174')/*发起反冲*/}</Button>
      <Button onClick={this.onCancel}>{messages('common.cancel')/*取消*/}</Button>
    </div>);
    return (
      <div className="new-payment-requisition-line">
        {
          alert_fail && <Alert
            message={messages('pay.key189')/*反冲金额*/ + " : " + backlashDetail.currency + this.filterMoney(backlashDetail.amount,queryCurrencyPrecision(backlashDetail.currency), true)}
            description={messages('pay.key224')/*当前状态：复核失败*/}
            type="error"
            showIcon
          />
        }
        {
          alert_warning && <Alert
            message={messages('pay.key178')/*复核中*/}
            description={messages('pay.key199')/*等待财务确认*/}
            type="warning"
            showIcon
          />
        }
        {
          alert_seccuss && <Alert
            message={messages('pay.key189')/*反冲金额*/ + " : " + backlashDetail.currency + this.filterMoney(backlashDetail.amount,queryCurrencyPrecision(backlashDetail.currency), true)}
            description={messages('pay.key200')/*当前状态：复核通过*/}
            type="success"
            showIcon
          />
        }
        <Form onSubmit={this.doBacklash}>
          <div className="common-item-title">{messages('pay.key201')/*业务单据信息*/}</div>
          <Row>
            <Col span={10} offset={1}>
              <FormItem label={messages('pay.key104')/*单据编号*/}>
                <span className="ant-form-text"><a onClick={() => {
                  this.viewDocumentDetail(documentInfo.documentId, documentInfo.documentCategory)
                }}>{documentInfo.documentCode}</a></span>
              </FormItem>
            </Col>
            <Col span={10} offset={1}>
              <FormItem label={messages('pay.key105')/*单据类型*/}>
                <span className="ant-form-text">{documentInfo.documentTypeName}</span>
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span={10} offset={1}>
              <FormItem label={messages('common.submit.date')/*提交日期*/}>
                <span className="ant-form-text">{(String)(documentInfo.documentDate).substr(0, 10)}</span>
              </FormItem>
            </Col>
            <Col span={10} offset={1}>
              <FormItem label={messages('pay.key15')/*申请人*/}>
                <span className="ant-form-text">{documentInfo.documentApplicant}</span>
              </FormItem>
            </Col>
          </Row>
          <div className="common-item-title">{messages('pay.key202')/*原支付信息*/}</div>
          <Row>
            <Col span={10} offset={1}>
              <FormItem label={messages('pay.key182')/*原付款流水号*/}>
                              <span className="ant-form-text"><a onClick={() => {
                                this.viewPayDetail(sourceDetail.id)
                              }}>{sourceDetail.billcode}</a>
                                </span>
              </FormItem>
            </Col>
            <Col span={10} offset={1}>
              <FormItem label={messages('pay.key101')/*付款日期*/}>
                <span className="ant-form-text">{(String)(sourceDetail.payDate).substr(0, 10)}</span>
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span={10} offset={1}>
              <FormItem label={messages('pay.key107')/*付款金额*/}>
                <span className="ant-form-text">{sourceDetail.currency} {this.filterMoney(sourceDetail.amount, queryCurrencyPrecision(sourceDetail.currency), true)}</span>
              </FormItem>
            </Col>
            <Col span={10} offset={1}>
              <FormItem label={messages('common.currency.rate')/*汇率*/}>
                <span className="ant-form-text">{sourceDetail.exchangeRate}</span>
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span={10} offset={1}>
              <FormItem label={messages('pay.key173')/*收款方名称*/}>
                <span className="ant-form-text">{sourceDetail.partnerName}</span>
              </FormItem>
            </Col>
            <Col span={10} offset={1}>
              <FormItem label={messages('pay.key27')/*收款方账号*/}>
                <span className="ant-form-text">{sourceDetail.payeeAccountNumber}</span>
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span={10} offset={1}>
              <FormItem label={messages('pay.key203')/*收款方户名*/}>
                <span className="ant-form-text">{sourceDetail.payeeAccountName}</span>
              </FormItem>
            </Col>
            <Col span={10} offset={1}>
              <FormItem label={messages('pay.key204')/*付款方账号*/}>
                <span className="ant-form-text">{sourceDetail.draweeAccountNumber}</span>
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span={10} offset={1}>
              <FormItem label={messages('pay.key205')/*付款方户名*/}>
                <span className="ant-form-text">{sourceDetail.draweeAccountName}</span>
              </FormItem>
            </Col>
            <Col span={10} offset={1}>
              <FormItem label={messages('pay.key25')/*付款方式*/}>
                <span className="ant-form-text">{sourceDetail.paymentTypeName}</span>
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span={20} offset={1}>
              <FormItem label={messages('common.remark')/*备注*/}>
                <span className="ant-form-text">{sourceDetail.remark}</span>
              </FormItem>
            </Col>
          </Row>
          {
            showDetail && <div>
              <div className="common-item-title">{messages('pay.key206')/*反冲信息*/}</div>
              <Row>
                <Col span={10} offset={1}>
                  <FormItem label={messages('pay.key181')/*反冲付款流水号*/}>
                    <span className="ant-form-text"><a onClick={() => {
                      this.viewPayDetail(backlashDetail.id)
                    }}>{backlashDetail.billcode}</a>
                    </span>
                  </FormItem>
                </Col>
                <Col span={10} offset={1}>
                  <FormItem label={messages('pay.key101')/*付款日期*/}>
                    <span className="ant-form-text">{(String)(backlashDetail.payDate).substr(0, 10)}</span>
                  </FormItem>
                </Col>
              </Row>
              <Row>
                <Col span={10} offset={1}>
                  <FormItem label={messages('common.amount')/*金额*/}>
                    <span className="ant-form-text">{backlashDetail.currency} {this.filterMoney(backlashDetail.amount, queryCurrencyPrecision(backlashDetail.currency), true)}</span>
                  </FormItem>
                </Col>
                <Col span={10} offset={1}>
                  <FormItem label={messages('common.currency.rate')/*汇率*/}>
                    <span className="ant-form-text">{backlashDetail.exchangeRate}</span>
                  </FormItem>
                </Col>
              </Row>
              <Row>
                <Col span={10} offset={1}>
                  <FormItem label={messages('pay.key173')/*收款方名称*/}>
                    <span className="ant-form-text">{backlashDetail.partnerName}</span>
                  </FormItem>
                </Col>
                <Col span={10} offset={1}>
                  <FormItem label={messages('pay.key27')/*收款方账号*/}>
                    <span className="ant-form-text">{backlashDetail.payeeAccountNumber}</span>
                  </FormItem>
                </Col>
              </Row>
              <Row>
                <Col span={10} offset={1}>
                  <FormItem label={messages('pay.key203')/*收款方户名*/}>
                    <span className="ant-form-text">{backlashDetail.payeeAccountName}</span>
                  </FormItem>
                </Col>
                <Col span={10} offset={1}>
                  <FormItem label={messages('pay.key204')/*付款方账号*/}>
                    <span className="ant-form-text">{backlashDetail.draweeAccountNumber}</span>
                  </FormItem>
                </Col>
              </Row>
              <Row>
                <Col span={10} offset={1}>
                  <FormItem label={messages('pay.key205')/*付款方户名*/}>
                    <span className="ant-form-text">{backlashDetail.draweeAccountName}</span>
                  </FormItem>
                </Col>
                <Col span={10} offset={1}>
                  <FormItem label={messages('pay.key25')/*付款方式*/}>
                    <span className="ant-form-text">{backlashDetail.paymentTypeName}</span>
                  </FormItem>
                </Col>
              </Row>
              <Row>
                {
                  backlashDetailRemark
                  &&
                  <Col span={10} offset={1}>
                    <FormItem label={messages('common.remark')/*备注*/}>
                      {getFieldDecorator('remarks', {
                        initialValue: backlashDetail.remark
                      })(
                        <TextArea autosize={{minRows: 2}} style={{minWidth: '100%'}}
                                  placeholder={messages('common.please.input')/*请输入*/} id="remarks"/>
                      )}
                    </FormItem>
                  </Col>
                }
                {
                  !backlashDetailRemark
                  &&
                  <Col span={10} offset={1}>
                    <FormItem label={messages('common.remark')/*备注*/}>
                      <span className="ant-form-text">{backlashDetail.remark}</span>
                    </FormItem>
                  </Col>
                }
                {/*<Col span={12} offset={0}>*/}
                  {/*{this.state.fileShow && <Upload attachmentType="PAYMENT"*/}
                                                  {/*fileNum={99}*/}
                                                  {/*multiple={true}*/}
                                                  {/*disabled={!backlashDetailRemark}*/}
                                                  {/*defaultOIDs={this.state.uploadOIDs}*/}
                                                  {/*uploadHandle={this.handleUpload}*/}
                                                  {/*defaultFileList={fileList}*/}
                  {/*/>}*/}
                {/*</Col>*/}
              </Row>
            </div>}
          <div style={{padding: 20, paddingBottom: 70}}>
            <ApproveHistory loading={this.state.historyLoading} infoData={this.state.approveHistory}></ApproveHistory>
          </div>
          <Modal visible={showChild}
                 footer={[
                   <Button key="back" size="large"
                           onClick={this.onClose}>{messages('common.back')/*返回*/}</Button>
                 ]}
                 width={1200}
                 closable={false}
                 onCancel={this.onClose}>
            <div>
              {this.wrapClose(PayDetail)}
            </div>
          </Modal>
          {showDetail ? newButton : approveButton}
        </Form>
      </div>
    )
  }
}


NewPayRefund.contextTypes = {
  router: React.PropTypes.object
};

const wrappedNewPayRefund = Form.create()(NewPayRefund);

export default wrappedNewPayRefund;
